package com.swt.gap.controller;

import com.swt.gap.common.PageResult;
import com.swt.gap.model.entity.Task;
import com.swt.gap.model.vo.MyTaskVO;
import com.swt.gap.model.vo.TaskInfoVO;
import com.swt.gap.model.vo.TaskUpdateVO;
import com.swt.gap.model.vo.TaskVO;
import com.swt.gap.model.vo.taskresult.AnalysisResultVO;
import com.swt.gap.model.vo.taskresult.TaskAnalysisVO;
import com.swt.gap.util.UserLoginUtils;
import com.swt.gap.service.TaskService;
import io.swagger.annotations.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;

@Api(tags = "300 任务相关")
@RestController
@RequestMapping("/task")
@Slf4j
public class TaskController {

    private final TaskService taskService;

    public TaskController(TaskService taskService) {
        this.taskService = taskService;
    }


    @PostMapping
    @ApiOperation(value = "新增任务", notes = "新增任务")
    @ApiImplicitParam(name = "task", dataType = "Task",paramType = "body", value = "任务信息")
    @ApiResponses({@ApiResponse(code = 201, message = "添加成功"),
                   @ApiResponse(code = 409, message = "已重名"),
                   @ApiResponse(code = 400, message = "非法请求")})
    public ResponseEntity addTask(@RequestBody Task task){
        //对任务名的校验
        String taskName = task.getTaskName();
        if(StringUtils.isNotBlank(taskName)){
            taskName = taskName.trim();
            if(taskName.length() > 20){
                return ResponseEntity.status(HttpStatus.BAD_REQUEST).body("名称长度不能超过20");
            }
            task.setTaskName(taskName);
        }else {
            return ResponseEntity.status(HttpStatus.BAD_REQUEST).body("名称不能为空");
        }
        //判断重名
        Boolean isRepeat = taskService.judgeTaskName(taskName, null);
        if(isRepeat){
            return ResponseEntity.status(HttpStatus.CONFLICT).body("任务名重名，不可用");
        }
        taskService.addNewTask(task);

        // service里新增一条数据到task表 同时task_user表插入参与者
        return ResponseEntity.status(HttpStatus.CREATED).body(task);
    }

    @GetMapping("/{taskId}")
    @ApiOperation(value = "获取任务", notes = "获取任务")
    @ApiImplicitParam(name = "taskId", dataType = "int",paramType = "path", value = "任务Id")
    @ApiResponses({@ApiResponse(code = 200, message = "ok", response = TaskInfoVO.class)})
    public ResponseEntity getTask(@PathVariable Integer taskId){
        // 查找 task表查基本信息，task_user查参与者id，再关联sys_user 获取user_name
        return ResponseEntity.ok(taskService.getTaskInfoById(taskId));
    }

    @PutMapping("/{taskId}")
    @ApiOperation(value = "编辑任务", notes = "编辑任务")
    @ApiImplicitParams ({
            @ApiImplicitParam(name = "taskId", dataType = "int",paramType = "path", value = "任务Id"),
            @ApiImplicitParam(name = "task", dataType = "TaskUpdateVO",paramType = "body", value = "任务信息")
    })
    @ApiResponses({@ApiResponse(code = 200, message = "ok"), @ApiResponse(code = 409, message = "已重名")})
    public ResponseEntity updateTask(@RequestBody TaskUpdateVO task, @PathVariable Integer taskId){
        Integer userId = UserLoginUtils.getUserId();
        if (!taskService.hasWritePermission(userId, taskId)) {
            return ResponseEntity.status(HttpStatus.FORBIDDEN).body("无操作权限");
        }
        task.setTaskId(taskId);

        //对任务名的校验
        String taskName = task.getTaskName();
        if(StringUtils.isNotBlank(taskName)){
            taskName = taskName.trim();
            if(taskName.length() > 20){
                return ResponseEntity.status(HttpStatus.BAD_REQUEST).body("名称长度不能超过20");
            }
            task.setTaskName(taskName);
        }else {
            return ResponseEntity.status(HttpStatus.BAD_REQUEST).body("名称不能为空");
        }

        //判断重名
        Boolean isRepeat = taskService.judgeTaskName(task.getTaskName(), taskId);
        if(isRepeat){
            return ResponseEntity.status(HttpStatus.CONFLICT).body("任务名重名，不可用");
        }
        taskService.updateTaskInfo(task);
        //   task_user表先清空taskId相关 再全量插入
        return ResponseEntity.ok(task);
    }

    @DeleteMapping("recycle-bin/{taskId}")
    @ApiOperation(value = "删除任务到回收站", notes = "删除任务到回收站")
    @ApiImplicitParam(name = "taskId", dataType = "int",paramType = "path", value = "任务Id")
    @ApiResponses({@ApiResponse(code = 200, message = "ok")})
    public ResponseEntity putTaskToRecycleBin(@PathVariable Integer taskId){
        Integer userId = UserLoginUtils.getUserId();
        if (!taskService.hasWritePermission(userId, taskId)) {
            return ResponseEntity.status(HttpStatus.FORBIDDEN).body("无操作权限");
        }
        taskService.putTaskToRecycleBin(taskId);
        // 查找 task表 is_deleted = true
        return ResponseEntity.ok("成功放入回收站");
    }

    @DeleteMapping
    @ApiOperation(value = "彻底删除任务", notes = "彻底删除任务可多选")
    @ApiImplicitParam(name = "taskIds", dataType = "array",paramType = "query", value = "任务Id集合", required = true)
    @ApiResponses({@ApiResponse(code = 200, message = "ok"), @ApiResponse(code = 400, message = "非法请求")})
    public ResponseEntity<String> deleteTasks(@RequestParam List<Integer> taskIds){

        if(CollectionUtils.isEmpty(taskIds)){
            return ResponseEntity.status(HttpStatus.BAD_REQUEST).body("没有选择任务信息");
        }
        for(Integer taskId : taskIds) {
            Integer userId = UserLoginUtils.getUserId();
            if (!taskService.hasWritePermission(userId, taskId)) {
                return ResponseEntity.status(HttpStatus.FORBIDDEN).body("无操作权限");
            }
        }

        taskService.deleteTasks(taskIds);
        return ResponseEntity.ok("删除成功");
    }

    @DeleteMapping("all")
    @ApiOperation(value = "彻底删除回收站中所有任务", notes = "彻底删除回收站中所有任务")
    @ApiResponses({@ApiResponse(code = 200, message = "ok"), @ApiResponse(code = 400, message = "非法请求")})
    public ResponseEntity deleteAllTasks(){
        int userId = UserLoginUtils.getUser().getUserId();
        PageResult<TaskVO> df = taskService.getDeleteTaskByKey(0,0,null,userId);
        List<Integer> taskIds = new ArrayList<>();
        for (TaskVO task:df.getList()) {
            taskIds.add(task.getTaskId());
        }
        if(CollectionUtils.isEmpty(taskIds)){
            return ResponseEntity.status(HttpStatus.BAD_REQUEST).body("没有可删除的任务");
        }
        taskService.deleteTasks(taskIds);
        return ResponseEntity.ok("删除成功");
    }

    @PutMapping("restore")
    @ApiOperation(value = "还原任务", notes = "还原任务")
    @ApiImplicitParam(name = "taskIds", dataType = "array",paramType = "query", value = "任务Id集合", required = true)
    @ApiResponses({@ApiResponse(code = 200, message = "ok"), @ApiResponse(code = 400, message = "非法请求")})
    public ResponseEntity restoreTasks(@RequestParam(required = true) List<Integer> taskIds){
        if(CollectionUtils.isEmpty(taskIds)){
            return ResponseEntity.status(HttpStatus.BAD_REQUEST).body("没有选择任务信息");
        }
        taskService.restoreTasks(taskIds);
        return ResponseEntity.ok("还原成功");
    }
    @PutMapping("restoreAll")
    @ApiOperation(value = "还原回收站中所有任务", notes = "还原回收站中所有任务")
    @ApiResponses({@ApiResponse(code = 200, message = "ok"), @ApiResponse(code = 400, message = "非法请求")})
    public ResponseEntity restoreAllTasks(){
        int userId = UserLoginUtils.getUser().getUserId();
        PageResult<TaskVO> df = taskService.getDeleteTaskByKey(0,0,null,userId);
        List<Integer> taskIds = new ArrayList<>();
        for (TaskVO task:df.getList()) {
            taskIds.add(task.getTaskId());
        }
        if(CollectionUtils.isEmpty(taskIds)){
            return ResponseEntity.status(HttpStatus.BAD_REQUEST).body("没有可还原的任务");
        }
        taskService.restoreTasks(taskIds);
        return ResponseEntity.ok("还原成功");
    }



    @GetMapping("/created-task")
    @ApiOperation(value = "我创建的任务", notes = "我创建的任务")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "keyword", dataType = "String", value = "输入的搜索条件, 无搜索时不传此参数"),
            @ApiImplicitParam(name = "pageNum", dataType = "int", value = "获取的当前页码，默认从第一页开始"),
            @ApiImplicitParam(name = "pageSize", dataType = "int", value = "每页的条数")
            })
    @ApiResponses({@ApiResponse(code = 200, message = "ok", response = MyTaskVO.class)})
    public ResponseEntity listCreatedTask(@RequestParam(required = false) String keyword,
                                          @RequestParam(value = "pageNum", defaultValue = "1")Integer pageNum,
                                          @RequestParam(value = "pageSize", defaultValue = "10")  Integer pageSize){
        //todo  返回 List<Task>
        int userId = UserLoginUtils.getUser().getUserId();
        return ResponseEntity.ok(taskService.getTaskByKey(pageNum,pageSize,keyword,userId));
    }

//    @GetMapping("/participate-task")
//    @ApiOperation(value = "参与的任务 列表", notes = "参与的任务")
//    @ApiImplicitParams({
//            @ApiImplicitParam(name = "keyword", dataType = "String", value = "输入的搜索条件, 无搜索时不传此参数"),
//            @ApiImplicitParam(name = "pageNum", dataType = "int", value = "获取的当前页码，默认从第一页开始"),
//            @ApiImplicitParam(name = "pageSize", dataType = "int", value = "每页的条数")
//    })
//    @ApiResponses({@ApiResponse(code = 200, message = "ok", response = MyTaskVO.class)})
//    public ResponseEntity listParticipateTask(HttpServletRequest request,
//                                              @RequestParam(required = false) String keyword,
//                                              @RequestParam(value = "pageNum",defaultValue = "1") Integer pageNum,
//                                              @RequestParam(value = "pageSize",defaultValue = "10") Integer pageSize){
//
//        //todo  返回 List<Task>
//        int userId = UserLoginUtils.getUser().getUserId();
//        return ResponseEntity.ok(taskService.getJoinTaskByKey(pageNum,pageSize,keyword,userId));
//    }

    @GetMapping("/processing-task")
    @ApiOperation(value = "进行中的任务 列表", notes = "进行中的任务")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "keyword", dataType = "String", value = "输入的搜索条件, 无搜索时不传此参数"),
            @ApiImplicitParam(name = "pageNum", dataType = "int", value = "获取的当前页码，默认从第一页开始"),
            @ApiImplicitParam(name = "pageSize", dataType = "int", value = "每页的条数")
    })
    @ApiResponses({@ApiResponse(code = 200, message = "ok", response = TaskVO.class, responseContainer = "List")})
    public ResponseEntity listProcessingTask(@RequestParam(required = false) String keyword,
                                             @RequestParam(value = "pageNum",defaultValue = "1") Integer pageNum,
                                             @RequestParam(value = "pageSize",defaultValue = "10") Integer pageSize){

        //todo  返回 List<Task>
        int userId = UserLoginUtils.getUser().getUserId();
        return ResponseEntity.ok(taskService.getTaskByStatus(pageNum,pageSize,keyword,userId,1));
    }

    @GetMapping("/finished-task")
    @ApiOperation(value = "已结束的任务 列表", notes = "已结束的任务")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "keyword", dataType = "String", value = "输入的搜索条件, 无搜索时不传此参数"),
            @ApiImplicitParam(name = "pageNum", dataType = "int", value = "获取的当前页码，默认从第一页开始"),
            @ApiImplicitParam(name = "pageSize", dataType = "int", value = "每页的条数")
    })
    @ApiResponses({@ApiResponse(code = 200, message = "ok", response = TaskVO.class, responseContainer = "List")})
    public ResponseEntity listFinishedTask(@RequestParam(required = false) String keyword,
                                           @RequestParam(value = "pageNum",defaultValue = "1") Integer pageNum,
                                           @RequestParam(value = "pageSize",defaultValue = "10") Integer pageSize){
        //todo  返回 List<Task>
        int userId = UserLoginUtils.getUser().getUserId();
        return ResponseEntity.ok(taskService.getTaskByStatus(pageNum,pageSize,keyword,userId,0));
    }

    @GetMapping("/finished-delete")
    @ApiOperation(value = "已删除的任务 列表", notes = "已删除的任务")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "keyword", dataType = "String", value = "输入的搜索条件, 无搜索时不传此参数"),
            @ApiImplicitParam(name = "pageNum", dataType = "int", value = "获取的当前页码，默认从第一页开始"),
            @ApiImplicitParam(name = "pageSize", dataType = "int", value = "每页的条数")
    })
    @ApiResponses({@ApiResponse(code = 200, message = "ok", response = TaskVO.class, responseContainer = "List")})
    public ResponseEntity listDeleteTask(@RequestParam(required = false) String keyword,
                                           @RequestParam(value = "pageNum",defaultValue = "1") Integer pageNum,
                                           @RequestParam(value = "pageSize",defaultValue = "10") Integer pageSize){
        int userId = UserLoginUtils.getUser().getUserId();
        return ResponseEntity.ok(taskService.getDeleteTaskByKey(pageNum,pageSize,keyword,userId));
    }


    @PutMapping("status/{taskId}")
    @ApiOperation(value = "启动或结束任务", notes = "由管理员或创建者启动或结束任务")
    @ApiImplicitParams({@ApiImplicitParam(name = "taskId", dataType = "int",paramType = "path", value = "任务Id"),
                        @ApiImplicitParam(name = "status", dataType = "int",paramType = "query", value = "任务状态，1为进行中，0为结束")
    })
    @ApiResponses({@ApiResponse(code = 200, message = "ok"), @ApiResponse(code = 403, message = "没有权限")})
    public ResponseEntity updateTaskStatus(@PathVariable Integer taskId, @RequestParam Integer status){
        Integer userId = UserLoginUtils.getUserId();
        if (!taskService.hasWritePermission(userId, taskId)) {
            return ResponseEntity.status(HttpStatus.FORBIDDEN).body("无操作权限");
        }
        taskService.updateStatus(taskId, status);
        if(status.equals(1)){
            return ResponseEntity.ok("启动成功");
        }
        return ResponseEntity.ok("结束成功");
    }

//
//    @GetMapping
//    @ApiOperation(value = "获取任务名列表", notes = "获取任务名列表")
//    @ApiResponses({@ApiResponse(code = 200, message = "ok", response = Task.class, responseContainer = "List")})
//    public ResponseEntity listTaskName(){
//        return ResponseEntity.ok(taskService.listTaskByCreatedUserId(UserLoginUtils.getUser().getUserId()));
//    }


    @GetMapping("/access/processing-task")
    @ApiOperation(value = "分析中心首页搜索", notes = "分析中心首页搜索")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "keyword", dataType = "String", paramType = "query", value = "输入的搜索条件")
    })
    @ApiResponses({@ApiResponse(code = 200, message = "ok", response = Task.class, responseContainer = "List"),
                   @ApiResponse(code = 400, message = "请求失败")})
    public ResponseEntity listAccessTask(@RequestParam String keyword){
        if (StringUtils.isBlank(keyword)) {
            return ResponseEntity.status(HttpStatus.BAD_REQUEST).body("请输入搜索条件");
        }
        Integer userId = UserLoginUtils.getUserId();
        return ResponseEntity.ok(taskService.getAccessTask(keyword, userId));
    }


    @PostMapping("/{taskId}")
    @ApiOperation(value = "添加分析时间记录", notes = "添加分析时间记录")
    @ApiImplicitParam(name = "taskId", dataType = "int", paramType = "path", value = "进入分析的任务id")
    @ApiResponses({@ApiResponse(code = 200, message = "ok")})
    public ResponseEntity updateAccessLog(@PathVariable Integer taskId){
        Integer userId = UserLoginUtils.getUserId();
        return ResponseEntity.ok(taskService.updateAccessLog(taskId,userId));
    }


    @GetMapping("/last-analysis-task")
    @ApiOperation(value = "近期分析的任务", notes = "近期分析的任务")
    @ApiResponses({@ApiResponse(code = 200, message = "ok", response = TaskAnalysisVO.class, responseContainer = "List")})
    public ResponseEntity getLastAnalysisTasks(){
        Integer userId = UserLoginUtils.getUserId();
        return ResponseEntity.ok(taskService.getLastAnalysisTasks(userId));
    }

    @GetMapping("/last-analysis-result")
    @ApiOperation(value = "近期分析结果", notes = "近期分析结果" )
    @ApiResponse(code = 200, message = "ok", response = AnalysisResultVO.class, responseContainer = "List")
    public ResponseEntity getLastAnalysisResults(){
        Integer userId = UserLoginUtils.getUserId();
        return ResponseEntity.ok(taskService.getLastAnalysisResults(userId));
    }


    @GetMapping("/read-permission")
    @ApiOperation(value = "获取读权限", notes = "获取读权限" )
    @ApiImplicitParams({
            @ApiImplicitParam(name = "taskId", dataType = "int", paramType = "query", value = "任务id"),
            @ApiImplicitParam(name = "password", dataType = "string", paramType = "query", value = "密码")
    })
    @ApiResponse(code = 200, message = "ok", response = Boolean.class)
    public ResponseEntity<Boolean> getReadPerm(@RequestParam Integer taskId, @RequestParam String password){
        return ResponseEntity.ok(taskService.getReadPerm(taskId, password));
    }

    @GetMapping("/access-task")
    @ApiOperation(value = "获取登录用户可查看的所有任务", notes = "获取登录用户可查看的所有任务 ，可指定进行中、结束等状态")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "keyword", dataType = "String", value = "输入的搜索条件, 无搜索时不传此参数"),
            @ApiImplicitParam(name = "pageNum", dataType = "int", value = "获取的当前页码，默认从第一页开始"),
            @ApiImplicitParam(name = "pageSize", dataType = "int", value = "每页的条数"),
            @ApiImplicitParam(name = "status", dataType = "int", value = "1 进行中 0结束 不传则全部 "),
    })
    @ApiResponses({@ApiResponse(code = 200, message = "ok", response = TaskVO.class, responseContainer = "List")})
    public ResponseEntity listAccessTask(@RequestParam(required = false) String keyword,
                                         @RequestParam(required = false) Integer status,
                                             @RequestParam(value = "pageNum",defaultValue = "1") Integer pageNum,
                                             @RequestParam(value = "pageSize",defaultValue = "10") Integer pageSize){

        //todo  返回 List<Task>
        int userId = UserLoginUtils.getUser().getUserId();
        return ResponseEntity.ok(taskService.getTaskByStatus(pageNum,pageSize,keyword,userId,status));
    }
}
